import React, { Component } from 'react';
import Avatar from 'material-ui/Avatar';
import Dialog from 'material-ui/Dialog';
import FontIcon from 'material-ui/FontIcon';
import MenuItem from 'material-ui/MenuItem';
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import DatePicker from 'material-ui/DatePicker';
import SelectField from 'material-ui/SelectField';
import CircularProgress from 'material-ui/CircularProgress';

import Corp from '../Utils/Corp';
import CONFIG from '../../config';
import { errorHandle } from '../Utils/ErrorHandle';
import { checkHttpStatus, parseJSON, postJsonMethod } from '../../redux/Helper';
import { DateTimeFormat, getDefaultTime, timeToStr, cutDateTime } from '../Utils/Helper';

const theme = ['派对', '旅行', '假期', '生日', '学习', '运动', '美食', '公益', '其他'];
let time = [];

for (var i = 0; i <= 23; i++) {
  let timeStr;
  let timeStrH;
  if (i < 10) {
    timeStr = '0' + i + ':00';
    timeStrH = '0' + i + ':30';
  } else {
    timeStr = i + ':00';
    timeStrH = i + ':30';
  }
  time.push(timeStr);
  time.push(timeStrH);
}

export default class NewActivity extends Component {
  initialState = {
    // 如果为编辑模式，为活动id
    id: null,
    // 是否为编辑模式
    isEdit: false,
    // 正在提交
    isReferring: false,
    // 正在拉取
    isFetching: false,
    // 选择结束时间
    isSelectEndTime: false,
    // 开启图片编辑器
    openCorp: false,
    // 活动封面的原画*0.6
    coverCanvas: null,
    // 表单数据
    cover: null,
    title: null,
    theme: '派对',
    date: new Date(),
    time: getDefaultTime(),
    endDate: new Date(),
    endTime: getDefaultTime(),
    address: null,
    numberOfPeople: null,
    details: null,
    error: {},
  };

  constructor(props) {
    super(props);
    this.state = this.initialState;
  }
  
  componentWillReceiveProps(nextProps) {
    if (nextProps.method == 'edit') {
      let startTime = cutDateTime(nextProps.data.start_time);
      let endTime;

      if (nextProps.data.end_time) {
        endTime = cutDateTime(nextProps.data.end_time);
        this.setState({
          endDate: endTime.date,
          endTime: endTime.time,
          isSelectEndTime: true
        });
      }

      this.setState({
        isEdit: true,
        id: nextProps.data.id,
        title: nextProps.data.title,
        theme: nextProps.data.theme,
        cover: nextProps.data.cover,
        date: startTime.date,
        time: startTime.time,
        address: nextProps.data.address,
        numberOfPeople: nextProps.data.number_of_people,
        details: nextProps.data.details,
      });
    }
  }

  /**
   * 修改text表单值
   */
  handleChangeText = (name, event, value) => {
    this.setState({[name]: value});
  };

  /**
   * 修改select表单值
   */
  handleChangeSelect = (name, event, index, value) => {
    this.setState({[name]: value});
  };

  /**
   * 修改canvas的base64值
   */
  handleChangeCanvas = (event, name, value, canvas) => {
    let canvasToBase64 = canvas.toDataURL('image/jpeg', 0.6);
    this.setState({[name]: value, [name + 'Canvas']: canvasToBase64});
  };

  /**
   * 直接修改state
   */
  handleSetState = (name, value) => {
    this.setState({[name]: value});
  };

  /**
   * 返回表单数据
   */
  returnPostData = () => {
    let cover = this.state.cover;
    let start = timeToStr(this.state.date, this.state.time);
    let end = timeToStr(this.state.endDate, this.state.endTime);

    if (this.state.coverCanvas) {
      cover = this.state.coverCanvas;
    }
    
    if (!this.state.isSelectEndTime) {
      end = null;
    }

    return {
      cover: cover,
      title: this.state.title,
      theme: this.state.theme,
      start_time: start,
      end_time: end,
      address: this.state.address,
      number_of_people: this.state.numberOfPeople,
      details: this.state.details,
      user_id: this.props.userId
    };
  };

  /**
   * 关闭dialog
   */
  closeDialog = () => {
    this.setState(this.initialState);
    this.props.handleClose('openNewActivity');
  };

  /**
   * 创建活动
   */
  create = () => {
    let data = this.returnPostData();
    let url = `${CONFIG.apiHost}/api/activity?token=${this.props.token}`;

    this.setState({isReferring: true});
    fetch(url, postJsonMethod(data))
    .then(checkHttpStatus)
    .then(parseJSON)
    .then(res => {
      this.setState({isReferring: false})
      this.closeDialog();
      this.props.replaceTo('/activity/me');
      this.sendReloadEvent();
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        this.setState({isReferring: false, error: v.msg});
        if (v.error) {
          this.props.tokenExpired();
        }
      })
    })
  };

  /**
   * 编辑活动
   */
  edit = () => {
    let data = this.returnPostData();
    let url = `${CONFIG.apiHost}/api/activity/${this.state.id}?token=${this.props.token}`;

    this.setState({isReferring: true});
    fetch(url, postJsonMethod(data))
    .then(checkHttpStatus)
    .then(parseJSON)
    .then(res => {
      this.setState({isReferring: false})
      this.closeDialog();
      this.sendReloadEvent();
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        this.setState({isReferring: false, error: v.msg});
        if (v.error) {
          this.props.tokenExpired();
        }
      })
    })
  };

  /**
   * 发送重载事件至由我发布页面
   */
  sendReloadEvent = () => {
    var evt = new CustomEvent('reloadActivityFromMe');
    window.dispatchEvent(evt);
  };

  render() {
    const actions = [
      <FlatButton
        label="取消"
        primary={true}
        onTouchTap={this.closeDialog}
      />,
      <div className="pull-right" style={{width: 88}}>
        {this.state.isReferring ? 
          <CircularProgress 
            style={{margin: 6, marginLeft: 32, marginRight: 32}}
            size={24}
          />
        : 
          <FlatButton
            label={this.state.isEdit ? '修改' : '发布'}
            primary={true}
            onTouchTap={this.state.isEdit ? this.edit : this.create}
          />
        }
      </div>,
    ];

  	return (
  	  <Dialog
        modal={false}
        actions={actions}
        open={this.props.open}
        onRequestClose={this.closeDialog}
        autoScrollBodyContent={true}
        autoDetectWindowHeight={false}
        contentStyle={{width: '100%', maxWidth: 560}}
        overlayStyle={{backgroundColor: 'rgba(0,0,0,0.12)'}}
      >
        <EditCover
          userImg={this.props.userImg}
          color500={this.props.color500}
          cover={this.state.cover}
          error={this.state.error}
          handleOpen={this.handleSetState.bind(this, 'openCorp', true)}
        />
        <EditTitleTheme
          title={this.state.title}
          theme={this.state.theme}
          error={this.state.error}
          handleChangeText={this.handleChangeText}
          handleChangeSelect={this.handleChangeSelect}
        />
        <EditStartTime
          date={this.state.date}
          time={this.state.time}
          handleSetState={this.handleSetState}
          handleChangeText={this.handleChangeText}
          handleChangeSelect={this.handleChangeSelect}
          isSmallViewport={this.props.isSmallViewport}
        />
        {this.state.isSelectEndTime ? 
          <EditEndTime
            date={this.state.endDate}
            time={this.state.endTime}
            handleSetState={this.handleSetState}
            handleChangeText={this.handleChangeText}
            handleChangeSelect={this.handleChangeSelect}
            isSelectEndTime={this.state.isSelectEndTime}
            isSmallViewport={this.props.isSmallViewport}
          /> : ''
        }
        <EditAddressNum
          error={this.state.error}
          address={this.state.address}
          numberOfPeople={this.state.numberOfPeople}
          handleChangeText={this.handleChangeText}
        />
        <EditDetails
          error={this.state.error}
          details={this.state.details}
          handleChangeText={this.handleChangeText}
        />
        <Corp 
          method={'cover'}
          open={this.state.openCorp}
          handleChange={this.handleChangeCanvas}
          isSmallViewport={this.props.isSmallViewport}
          handleOpenSnackbar={this.props.handleOpenSnackbar}
          handleClose={this.handleSetState.bind(this, 'openCorp', false)}
        />
      </Dialog>
  	);
  }
};

class EditCover extends Component {
  render() {
    let style = {
      position: 'relative',
      height: 224,
      marginTop: -24,
      marginLeft: -24,
      marginRight: -24,
      marginBottom: 12,
      borderBottomWidth: 1,
      borderBottomColor: 'rgb(224, 224, 224)',
      borderBottomStyle: 'solid',
      background: 'url('+this.props.cover+')',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      backgroundSize: 'cover'
    };

    return (
      <div style={style}>
        <Avatar src={this.props.userImg} style={styles.userImg} />
        <IconButton
          touch={true}
          style={styles.btn}
          tooltip="贴上你的照片或选择活动封面"
          tooltipPosition="top-left"
          onClick={this.props.handleOpen}
        >
          <FontIcon 
            className="icon-camera" 
            color={this.props.color500}
          />
        </IconButton>
        <div style={styles.error}>{errorHandle(this.props.error, 'cover')}</div>
      </div>
    );
  }
};

class EditTitleTheme extends Component {
  render() {
    return (
      <div className='row'>
        <div className='col-xs-8'>
          <TextField 
            fullWidth={true}
            hintText='活动标题'
            defaultValue={this.props.title}
            errorText={errorHandle(this.props.error, 'title')}
            onChange={this.props.handleChangeText.bind(this, 'title')}
          />
        </div>
        <div className='col-xs-4'>
          <SelectField
            maxHeight={200}
            autoWidth={true}
            hintText='选择主题'
            style={{width: 'auto'}}
            value={this.props.theme}
            onChange={this.props.handleChangeSelect.bind(this, 'theme')}
          >
            {theme.map((v, i) => {
              return (
                <MenuItem key={i} value={v} primaryText={v} />
              );
            })}
          </SelectField>
        </div>
      </div>
    );
  }
};

class EditStartTime extends Component {
  render() {
    return (
      <div className='row'>
        <div className='col-xs-8'>
          <div className='row'>
            <div className='col-xs-8'>
              <DatePicker
                locale='zh'
                autoOk={true}
                cancelLabel='取消'
                minDate={new Date()}
                floatingLabelText='开始时间'
                defaultDate={this.props.date}
                DateTimeFormat={DateTimeFormat}
                textFieldStyle={{width: '100%'}}
                onChange={this.props.handleChangeText.bind(this, 'date')}
              />
            </div>
            <div className='col-xs-4'>
              <SelectField
                value={this.props.time}
                maxHeight={200}
                autoWidth={true}
                iconStyle={{display: this.props.isSmallViewport ? 'none' : 'block'}}
                style={{width: '100%', marginTop: 24}}
                onChange={this.props.handleChangeSelect.bind(this, 'time')}
              >
                {time.map((v, i) => {
                  return (
                    <MenuItem key={i} value={v} primaryText={v} />
                  );
                })}
              </SelectField>
            </div>
          </div>
        </div>
        <div className='col-xs-4'>
          <IconButton
            style={{marginTop: 24}}
            iconClassName='icon-add'
            tooltip='设置结束时间'
            tooltipPosition='top-right'
            onTouchTap={this.props.handleSetState.bind(this, 'isSelectEndTime', true)}
          />
        </div>
      </div>
    );
  }
};

class EditEndTime extends Component {
  render() {
    return (
      <div className='row'>
        <div className='col-xs-8'>
          <div className='row'>
            <div className='col-xs-8'>
              <DatePicker
                locale='zh'
                autoOk={true}
                cancelLabel='取消'
                minDate={new Date()}
                floatingLabelText='结束时间'
                defaultDate={this.props.date}
                DateTimeFormat={DateTimeFormat}
                textFieldStyle={{width: '100%'}}
                onChange={this.props.handleChangeText.bind(this, 'endDate')}
              />
            </div>
            <div className='col-xs-4'>
              <SelectField
                value={this.props.time}
                maxHeight={200}
                autoWidth={true}
                style={{width: '100%', marginTop: 24}}
                iconStyle={{display: this.props.isSmallViewport ? 'none' : 'block'}}
                onChange={this.props.handleChangeSelect.bind(this, 'endTime')}
              >
                {time.map((v, i) => {
                  return (
                    <MenuItem key={i} value={v} primaryText={v} />
                  );
                })}
              </SelectField>
            </div>
          </div>
        </div>
        <div className='col-xs-4'>
          <IconButton
            style={{marginTop: 24}}
            iconClassName='icon-remove'
            tooltip='取消'
            tooltipPosition='top-right'
            onTouchTap={this.props.handleSetState.bind(this, 'isSelectEndTime', false)}
          />
        </div>
      </div>
    );
  }
};

class EditAddressNum extends Component {
  render() {
    return (
      <div className='row'>
        <div className='col-xs-8'>
          <TextField 
            fullWidth={true}
            hintText='地点(可选)'
            defaultValue={this.props.address}
            errorText={errorHandle(this.props.error, 'address')}
            onChange={this.props.handleChangeText.bind(this, 'address')}
          />
        </div>
        <div className='col-xs-4'>
          <TextField 
            style={{width: 88}}
            hintText='人数(可选)'
            defaultValue={this.props.numberOfPeople ? this.props.numberOfPeople : ''}
            errorText={errorHandle(this.props.error, 'number_of_people')}
            onChange={this.props.handleChangeText.bind(this, 'numberOfPeople')}
          />
        </div>
      </div>
    );
  }
};

class EditDetails extends Component {
  render() {
    return (
      <div className='row'>
        <div className='col-xs-12'>
          <TextField
            rows={2}
            multiLine={true}
            fullWidth={true}
            hintText='说明活动详情'
            floatingLabelText='详情(可选)'
            defaultValue={this.props.details}
            errorText={errorHandle(this.props.error, 'details')}
            onChange={this.props.handleChangeText.bind(this, 'details')}
          />
        </div>
      </div>
    );
  }
};

const styles = {
  userImg: {
    position: 'absolute',
    left: 24,
    top: 24
  },
  content: {
    paddingLeft: 24,
    paddingRight: 24
  },
  row: {
    marginBottom: 12
  },
  btn: {
    position: 'absolute',
    bottom: 12,
    right: 12
  },
  error: {
    position: 'absolute',
    left: 24,
    bottom: 24,
    height: 12,
    color: 'rgb(244,67,54)',
    fontSize: 12
  }
};